package com.dimbottom;

import com.dimbottom.dao.StudentDao;
import com.dimbottom.service.AutoSignInService;
import org.apache.log4j.Logger;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

import java.io.IOException;
import java.util.List;

/**
 * 这里使用了 Quartz 框架来执行定时任务，每天早上 8 点提交
 */
public class MainClass {

    private static final Logger mainLogger = Logger.getLogger(MainClass.class);
    private static final Logger jobLogger = Logger.getLogger(AutoSignInJob.class);

    public static class AutoSignInJob implements Job {
        @Override
        public void execute(JobExecutionContext context) throws JobExecutionException {
            AutoSignInService autoSignInService = new AutoSignInService();
            StudentDao studentDao = new StudentDao();
            List<String> studentCodeList = studentDao.queryAllStudentCode();
            if (studentCodeList == null || studentCodeList.size() == 0) {
                jobLogger.info("数据库不存在或无无数据，本次自动提交结束");
                return;
            }
            try {
                for (String studentCode : studentCodeList) {
                    autoSignInService.submit(studentCode);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) throws SchedulerException {
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
        JobDetail detail = JobBuilder.newJob(AutoSignInJob.class)
                .withIdentity("auto-sign-in")
                .build();
        CronTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("auto-sign-in")
                .withSchedule(CronScheduleBuilder.cronSchedule("0 0 8 * * ?")) // 每天 8 点打卡，参照
                .build();
        scheduler.scheduleJob(detail, trigger);
        mainLogger.info("自动签到程序启动，初始化完成。");
        scheduler.start();
    }

}
